<template>
  <div class="app-container">
    <!--用户数据-->

    <HkSearchform
      :data="searchFormObj.searchData"
      :field-list="searchFormObj.fieldList"
      :listTypeInfo="searchFormObj.listTypeInfo"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    ></HkSearchform>
    <el-row :gutter="10" class="mb8">
      <!--  v-if="!isUM" -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
              <el-button
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:user:edit']"
                >修改</el-button
              >
      </el-col>
      <el-col :span="1.5" v-if="!isUM">
        <el-button
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5" v-if="!isUM">
        <el-button
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button>
      </el-col> -->
      <!--          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
      ></right-toolbar>-->
    </el-row>
    <HkTable
      :total="total"
      :tableData="planList"
      :queryParams="queryParams"
      :tableColumns="qualtableLabel"
      :showIndex="true"
      :operate="true"
      :selection="true"
      class="targetTable"
      @changePage="getList"
      @handleSelectionChange="handleSelectionChange"
    >
      <template #role="scope" width="50">
        <el-tag size="mini" v-if="scope.row.role">{{ scope.row.role.name }}</el-tag>
      </template>
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          :active-value="acxtiveValue"
          :inactive-value="inactiveValue"
          @change="handleStatusChange(scope.row)"
          :disabled="scope.row.userType == 1 || isUM"
        ></el-switch>
      </template>
      <template #loginFlag="scope" width="50">
        <el-tag type="warning" size="mini" v-if="scope.row.loginFlag == -1">已锁定</el-tag>
        <el-tag type="success" size="mini" v-else-if="scope.row.loginFlag != -1">正常</el-tag>
      </template>
      <template #operate="scope">
        <el-button
          v-hasPermi="['system:user:add', 'system:user:edit']"
          @click="handleUpdate(scope.row)"
          type="text"
        >{{ (scope.row.userType == 1) ? '详情' : '修改' }}</el-button>
        <el-button
          v-hasPermi="['system:user:remove']"
          @click="handleDelete(scope.row)"
          type="text"
          v-if="scope.row.userType != 1"
        >删除</el-button>
        <el-dropdown
          @command="(command) => handleCommand(command, scope.row)"
          v-hasPermi="['system:user:edit']"
        >
          <span class="el-dropdown-link">
            <i class="el-icon-d-arrow-right el-icon--right"></i>更多
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              command="handleResetPwd(scope.row)"
              icon="el-icon-key"
              v-hasPermi="['system:user:edit']"
            >重置密码</el-dropdown-item>
            <el-dropdown-item
              command="handleUnlcok(scope.row)"
              icon="el-icon-circle-check"
              v-hasPermi="['system:user:edit']"
              :disabled="scope.row.loginFlag != -1"
            >解除锁定</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </HkTable>
    <!-- 新增和修改的对话框 -->
    <AddDialog
      ref="add_dia"
      :title="title"
      @submitForm="getList"
      :statusDict="statusDict"
      :deptOptions="deptOptions"
      :currentDeptNode="currentDeptId"
    />
    <!-- 导入的对话框 -->
    <import-dialog ref="import_dia" @refresh="getList" />
  </div>
</template>

<script>
import { listUser, changeUserStatus, delUser, resetUserPwd, unlockUserStatus } from '@/api/system/account'

import { treeselect } from '@/api/system/dept'
import HkSearchform from '@/components/HKSearchform/index.vue'
import HkTable from '@/components/HKTable/index.vue'
import AddDialog from './form'
import ImportDialog from './coms/importDialog.vue'
import { passwordRegx } from '@/utils/validate'

const isUM = window.loginType == 'UM'

export default {
  name: 'User',
  dicts: ['user_status'],
  components: { HkSearchform, HkTable, AddDialog, ImportDialog },
  data() {
    return {
      isUM,
      total: 0,
      // 弹出框的值标题
      title: '',
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        orgIds: ''
      },
      // 选中的id值们
      ids: '',
      // 选中的名称
      names: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      loading: false,
      // 部门树选项
      deptOptions: [],
      // 部门名称
      deptName: undefined,
      currentDeptId: '',
      statusDict: [],
      acxtiveValue:0,
      inactiveValue:-2,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //   搜索数据
      searchFormObj: {
        fieldList: [
          {
            label: '关键字',
            type: 'input',
            field: 'name',
            placeholder: '请输入用户名称/手机号码'
          },

          {
            label: '状态',
            type: 'select',
            field: 'status',
            list: 'statusBoxList',
            clearable: true
          },
          {
            label: '创建时间',
            type: 'dateRange',
            field: 'timetBox'
          }
        ],
        searchData: {},
        btnHidden: true,
        listTypeInfo: {
          statusBoxList: []
        },
        //  是否有额外的参数
        isNeedResetExtraParam: false
      },
      planList: [],
      qualtableLabel: [
        { label: '用户名称', param: 'name', width: '90' },
        { label: '账号名称', param: 'account', width: '90' },
        { label: '角色', param: 'role', type: 'slot', align: 'center' },
        // { label: "部门", param: "orgName" },
        // { label: "手机号码", param: "phone" },
        { label: '状态', param: 'status', type: 'slot' },
        { label: '锁定状态', param: 'loginFlag', type: 'slot' },
        { label: '创建时间', param: 'createDate' }
      ]
    }
  },

  methods: {
    onDictReady(dict) {
      this.searchFormObj.listTypeInfo.statusBoxList = dict.type.user_status
      this.statusDict = dict.type.user_status
      this.statusDict.forEach(i=>{
        if(i.label=='正常'){
          this.activeValue=JSON.parse(i.value)
        }else{
          this.inactiveValue=JSON.parse(i.value)
        }
      })
    },
    // 重置按钮
    handleReset() {
      this.queryParams = {}
      this.getList()
    },

    // 搜索按钮
    handleSearch(data) {
      if (data.timetBox) {
        data.endTime = data.timetBox[1]
        data.startTime = data.timetBox[0]
      }
      this.queryParams = data
      this.queryParams.size = 10
      this.queryParams.current = 1

      this.getList()
    },

    /** 查询用户列表 */
    getList(val) {
      this.loading = true
      this.queryParams = { ...this.queryParams, ...val }

      listUser(this.queryParams).then(res => {
        this.total = res.total
        this.planList = res.list
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.currentDeptId = response[0].id
        this.deptOptions = response
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id
      this.currentDeptId = data.id
      this.queryParams.size = 10
      // this.queryIds(this.queryParams, data.children, this.queryParams.orgIds)
      this.queryParams.current = 1
      this.getList()
    },
    // 节点递归函数
    queryIds(query, data, lists) {
      if (data) {
        data.forEach(item => {
          lists.push(item.id)
        })
        this.queryIds(query, data.children, lists)
      } else {
        return
      }
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status == '0' ? '启用' : '停用'
      this.$modal
        .confirm('确认要"' + text + '"' + row.name + '"用户吗？')
        .then(function() {
          return changeUserStatus(row.id, row.status)
        })
        .then(() => {
          this.$modal.msgSuccess(text + '成功')
        })
        .catch(function() {
          row.status = row.status == '0' ? 1 : 0
        })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      const index = command.indexOf('(')
      let ccomand = command.slice(0, index)
      switch (ccomand) {
        case 'handleResetPwd':
          this.handleResetPwd(row)
          break
        case 'handleUnlcok':
          this.handleUnlcok(row)
          break
        default:
          break
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.getTreeselect()
      this.$refs.add_dia.show('')
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getTreeselect()
      this.$refs.add_dia.show(row.id)
      this.title = '修改'
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输["' + row.account + '"]的新密码', '重置密码', {
        customClass: 'pwd-message-box',
        inputType: 'password',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        // inputPattern: passwordRegx,
        // inputErrorMessage: '密码需同时包含数字、大写字母、小写字母和特殊字符，且长度在8-15位字符之间'
      })
        .then(({ value }) => {
          resetUserPwd(row.id, value).then(response => {
            this.$modal.msgSuccess('修改密码成功')
          })
        })
        .catch(() => {})
    },
    /** 解除锁定操作 */
    handleUnlcok(row) {
      const name = row.name
      const userId = row.id
      this.$modal
        .confirm('是否确认解锁用户[' + name + ']的锁定？')
        .then(() => {
          unlockUserStatus(userId).then(resp => {
            this.getList()
            this.$modal.msgSuccess('解锁成功')
          })
        })
        .catch(() => {})
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.id
      this.$router.push('/system/user-auth/role/' + userId)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const names = row.name || this.names
      const userIds = row.id || this.ids
      this.$modal
        .confirm('是否确认删除所选账号？')
        .then(function() {
          return delUser(userIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {}, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import_dia.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(window.baseUrl+'system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .targetTable {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
}

.pwd-message-box {
  width: 500px !important;
}
</style>
